package com.compty.paint.manager;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.compty.core.hibernate.HibernateEntityDao;
import com.compty.core.page.Page;
import com.compty.paint.domain.Goods;
import com.compty.paint.domain.Painting;
import com.compty.paint.exception.OrderExistException;

/**
 * @Todo:商品manager类
 * @author: 朱庆辉
 * @CreateTime:2012-3-15 上午11:36:30
 */
public class GoodsManager  extends HibernateEntityDao<Goods>{
	
	private PaintingManager paintingManager;
	private BidManager bidManager;
	
	public void setPaintingManager(PaintingManager paintingManager) {
		this.paintingManager = paintingManager;
	}

	public void setBidManager(BidManager bidManager) {
		this.bidManager = bidManager;
	}

	/**
	 *@Todo:根据画家及作品标题查询商品
	 *@CreateTime:2012-2-29 下午05:20:16
	 * @param painterName 画家名称
	 * @param paintingTitle 作品标题
	 */
	@SuppressWarnings("unchecked")
	public Page queryGoodsByPainterNameAndTitle(final Integer curPage,final Integer pageSize,final String painterName,final String paintingTitle) {
		// TODO Auto-generated method stub
		
		List idList =  (List) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				
				String sql = "select g.id as goods_id from  t_goods g ,t_painting p,t_painter pa where g.painting_id=p.id and p.painterid = pa.id " 
						+ " and pa.name like ? and p.title like ? "
						+ " order by g.id desc limit "+(curPage-1)*pageSize +","+pageSize;
				
				SQLQuery query = session.createSQLQuery(sql);
				query.setString(0, "%"+painterName+"%");
				query.setString(1,"%"+paintingTitle+"%");
				
				List paintingIdList =  query.addScalar("goods_id", Hibernate.INTEGER).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
				return paintingIdList;
			}
	    });
		
		Integer totalCount =   (Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				
				String sql = "select count(*) as totalCount from  t_goods g ,t_painting p,t_painter pa where g.painting_id=p.id and p.painterid = pa.id " 
					+ " and pa.name like ? and p.title like ? ";
				
				SQLQuery query = session.createSQLQuery(sql);
				query.setString(0, "%"+painterName+"%");
				query.setString(1,"%"+paintingTitle+"%");
				
				Integer totalCount  =  (Integer) query.addScalar("totalCount",Hibernate.INTEGER).uniqueResult();
				return totalCount;
			}
	    });
		
		List<Goods> goodsList = new ArrayList<Goods>();
		for (Object object : idList) {
			
			Map goods_id_map = (Map) object;
			Integer goods_id = (Integer) goods_id_map.get("goods_id");
			
			Goods goods = findById(goods_id);
			goodsList.add(goods);
		}
		
		Page page = new Page();
		page.setResult(goodsList);
		page.setTotalCount(totalCount);
		page.setPageNo(curPage);
		page.setPageSize(pageSize);
		
		return page;
	}
	
	/**
	 *@Todo:由ID查询商品详细信息
	 *@CreateTime:2012-2-29 下午05:26:07
	 * @param id 商品编号
	 */
	public Goods findById(Serializable id){
		
		Goods goods = get(this.entityClass, id);
		if( goods != null){
			Long painting_id = goods.getPainting_id();
			if(painting_id != null){
				Painting painting = paintingManager.get(painting_id);
				goods.setPainting(painting);
			}
			return goods;
		}
		return null;
	}
	
	/**
	 *@Todo:根据作品ID删除商品
	 *@author:朱庆辉
	 *@CreateTime:2012-4-6 下午01:52:33
	 * @param painting_id 作品ID
	 * @throws OrderExistException 
	 */
	@SuppressWarnings("unchecked")
	public void removeByPaintingId(Serializable painting_id) throws OrderExistException {
		
		String hql = "from Goods where painting_id=?";
		
		List<Goods>  list = find(hql, painting_id);
		
		for (Goods goods : list) {
			
			if(goods != null){
				deleteById(goods.getId());
			}
		}
	}
	
	/**
	 * 删除商品及商品对应的拍品
	 * @param id 商品ID
	 * @throws OrderExistException 
	 * @throws OrderExistException 
	 */
	@SuppressWarnings("unchecked")
	public void deleteById(Serializable id) throws OrderExistException{
		
		String hql = "from OrderItem where goods.id = ?";
		List list = super.find(hql, id);
		if( list != null && list.size() >0){
			throw new OrderExistException("已生成关联订单,不能删除");
		}
		
		bidManager.removeByGoodsId(id);
		
		super.removeById(id);
	}

	/**
	 *@Todo:由作品ID查找商品
	 *@author:朱庆辉
	 *@CreateTime:2012-3-15 上午11:35:57
	 * @param paintingId 作品ID
	 * @return
	 */
	public Goods findByPaintingId(Long paintingId) {
		Goods goods = findUniqueBy("painting_id", paintingId);
		return goods;
	}

	@SuppressWarnings("unchecked")
	public void deleteGoodsByPaintingId(Long paintingId) {
		String hql = "from Goods where painting_id = ?";
		List<Goods>  list = find(hql, paintingId);
		for (Goods goods : list) {
			if( goods != null){
				Integer goodsId = goods.getId();
				hql = "from OrderItem where goods.id = ?";
				List orderItems = super.find(hql, goodsId);
				if( orderItems != null && orderItems.size() >0){
					
				}else{
					bidManager.removeByGoodsId(goodsId);
					super.removeById(goodsId);
				}
			}
		}
	}

}
